/******************************************************************************
@file:  Search.java
@author Ramesh Anandhan

DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
 ******************************************************************************/
package com.smartc.ui;

import java.util.ArrayList;
import java.util.Calendar;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.smartc.connection.HttpConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Search extends Activity implements OnClickListener {

	public static final int SEARCH_MORNING = 0x01;
	public static final int SEARCH_EVENING = 0x02;
	public static final int SEARCH_LMS_MMTS = 0x03;
	public static final int SEARCH_ROUTE = 0x04;
	public static final int SEARCH_TIME = 0x05;

	private static final String TAG = null;
	private static final int TIME_PICKER = 0;
	private TextView mTime = null;
	private Button mEditTime = null;

	private Spinner mCity = null;

	private TextView mEndLoc = null;
	private Spinner mEditEndLoc = null;

	private TextView mBPoint = null;
	private Spinner mEditBPoint = null;
	private Button mSubmit = null;

	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	private String mSelectedCity = null;
	private String mSelectedRoute = null;
	private String mSelectedLocation;

	private String mStartLocation = null;
	private String mEndLocation = null;
	private int mSearchType = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_1);

		mCityConnection = new HttpConnection();
		String domain = getResources().getString(R.string.domain);
		String query = getResources().getString(R.string.url_city_list);
		String url = domain + query;
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onCreate url:" + url);
		mCityConnection.setUrl(url);
		mCityConnection.clearParam();
		mCityConnection.AddHandler(mResponse);
		mCityConnection.Execute();

		Intent intent = getIntent();
		String search = intent.getStringExtra("search");

		mCity = (Spinner) findViewById(R.id.search_city);
		mCity.setEnabled(false);
		mCity.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);

				if (position == 0){
					
					if (mSearchType == SEARCH_ROUTE)
						mSelectedRoute = null;
					else if (mSearchType == SEARCH_TIME)
						mSelectedLocation = null;
					else{
						mEndLocation = null;
						mStartLocation = null;
					}
										
					String empty[] = new String[0];
					mEditEndLoc.setAdapter(new ArrayAdapter(Search.this,
							R.layout.simple_spinner_item, empty));
					mEditEndLoc.setEnabled(false);
					mEditBPoint.setAdapter(new ArrayAdapter(Search.this,
							R.layout.simple_spinner_item, empty));
					mEditBPoint.setEnabled(false);
					return;
				}
				mSelectedCity = mResponse.mCity_Id.get(--position);

				String domain = getResources().getString(R.string.domain);
				String query = null;
				if (mSearchType == Search.SEARCH_ROUTE) {
					query = getResources().getString(R.string.url_route_list);
				} else if (mSearchType == Search.SEARCH_TIME) {
					query = getResources().getString(
							R.string.url_location_by_cityid);
				} else {
					query = getResources().getString(
							R.string.url_transport_search_location);
				}
				String url = domain + query;

				mCityConnection.setUrl(url);
				mCityConnection.clearParam();
				mCityConnection.AddParam("idCity", mSelectedCity);
				mCityConnection.Execute();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		mEndLoc = (TextView) findViewById(R.id.text_elocation);
		mEditEndLoc = (Spinner) findViewById(R.id.search_elocation);
		mEditEndLoc.setEnabled(false);
		mEditEndLoc.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);

				if (position == 0){
					if (mSearchType == SEARCH_ROUTE)
						mSelectedRoute = null;
					else if (mSearchType == SEARCH_TIME)
						mSelectedLocation = null;
					else
						mEndLocation = null;
					return;
				}
				if (mSearchType == SEARCH_ROUTE)
					mSelectedRoute = mResponse.mRoute_List_id.get(--position);
				else if (mSearchType == SEARCH_TIME)
					mSelectedLocation = mResponse.mBoarding_Id.get(--position);
				else
					mEndLocation = mResponse.mBoarding_Id.get(--position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		mBPoint = (TextView) findViewById(R.id.text_search_bpoint);
		mEditBPoint = (Spinner) findViewById(R.id.search_bpoint);
		mEditBPoint.setEnabled(false);
		mEditBPoint.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);

				if (position == 0){
					if (mSearchType == SEARCH_TIME)
						mSelectedLocation = null;
					else
						mStartLocation = null;
					return;
				}

				if (mSearchType == SEARCH_TIME)
					mSelectedLocation = mResponse.mBoarding_Id.get(--position);
				else
					mStartLocation = mResponse.mBoarding_Id.get(--position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});
		mTime = (TextView) findViewById(R.id.text_time);
		mEditTime = (Button) findViewById(R.id.search_time);
		mSubmit = (Button) findViewById(R.id.search_submit);
		mSubmit.setOnClickListener(this);
		mEditTime.setOnClickListener(this);
		if (search.equals("route")) {

			mEndLoc.setText("Select Route");
			mTime.setVisibility(View.INVISIBLE);
			mEditTime.setVisibility(View.INVISIBLE);
			mSearchType = SEARCH_ROUTE;
			mBPoint.setVisibility(View.INVISIBLE);
			mEditBPoint.setVisibility(View.INVISIBLE);

		} else if (search.equals("time")) {
			mSearchType = SEARCH_TIME;
			mEndLoc.setVisibility(View.INVISIBLE);
			mEditEndLoc.setVisibility(View.INVISIBLE);
		} else {
			mSearchType = Integer.parseInt(search);
			mTime.setVisibility(View.INVISIBLE);
			mEditTime.setVisibility(View.INVISIBLE);
		}
	}

	public class ResponseHandler extends DefaultHandler {

		// private boolean Cities = false;
		private boolean nmCity = false;
		private boolean idCity = false;

		// private boolean Routes = false;
		// private boolean Route = false;
		private boolean nmRoute = false;
		private boolean idRoute = false;

		// private boolean BoardingLocations = false;
		private boolean nmBoardingLocation = false;
		private boolean idBoardingLocation = false;

		public ArrayList<String> mCity_List = new ArrayList<String>();
		public ArrayList<String> mCity_Id = new ArrayList<String>();
		public ArrayList<String> mRoute_List = new ArrayList<String>();
		public ArrayList<String> mRoute_List_id = new ArrayList<String>();
		public ArrayList<String> mBoarding_List = new ArrayList<String>();
		public ArrayList<String> mEnd_List = new ArrayList<String>();
		public ArrayList<String> mBoarding_Id = new ArrayList<String>();
		public String _mStatus;
		public String _mMessage;

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.nmCity) {
				mCity_List.add(new String(ch, start, length));
			} else if (this.idCity) {
				mCity_Id.add(new String(ch, start, length));
			} else if (this.nmRoute) {
				mRoute_List.add(new String(ch, start, length));
			} else if (this.idRoute) {
				mRoute_List_id.add(new String(ch, start, length));
			} else if (this.idBoardingLocation) {
				mBoarding_Id.add(new String(ch, start, length));
			} else if (this.nmBoardingLocation) {
				mBoarding_List.add(new String(ch, start, length));
				mEnd_List.add(new String(ch, start, length));
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equals("Cities")) {
				// this.Cities = false;
				Message myMessage = new Message();
				myMessage.obj = "CITY";
				handler.sendMessage(myMessage);
			} else if (localName.equals("nmCity")) {
				this.nmCity = false;
			} else if (localName.equals("idCity")) {
				this.idCity = false;
			} else if (localName.equals("Routes")) {
				// this.Routes = false;
				Message myMessage = new Message();
				myMessage.obj = "ROUTE";
				handler.sendMessage(myMessage);
			} else if (localName.equals("Route")) {
				// this.Route = false;
			} else if (localName.equals("idRoute")) {
				this.idRoute = false;
			} else if (localName.equals("nmRoute")) {
				this.nmRoute = false;
			} else if (localName.equals("BoardingLocations")) {
				// this.BoardingLocations = false;
				Message myMessage = new Message();
				myMessage.obj = "BLOCATIONS";
				handler.sendMessage(myMessage);
			} else if (localName.equals("nmBoardingLocation")) {
				this.nmBoardingLocation = false;
			} else if (localName.equals("idBoardingLocation")) {
				this.idBoardingLocation = false;
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("Cities")) {
				// this.Cities = true;
				mCity_Id.clear();
				mCity_List.clear();
				mCity_List.add("select city");
			} else if (localName.equals("nmCity")) {
				this.nmCity = true;
			} else if (localName.equals("idCity")) {
				this.idCity = true;
			} else if (localName.equals("Routes")) {
				// this.Routes = true;
				mRoute_List.clear();
				mRoute_List_id.clear();
				mRoute_List.add("select route");
			} else if (localName.equals("Route")) {
				// this.Route = true;
			} else if (localName.equals("nmRoute")) {
				this.nmRoute = true;
			} else if (localName.equals("idRoute")) {
				this.idRoute = true;
			} else if (localName.equals("BoardingLocations")) {
				// this.BoardingLocations = true;
				mBoarding_List.clear();
				mBoarding_List.add("select boardingpoint");
				mBoarding_Id.clear();
				mEnd_List.clear();
				mEnd_List.add("select Endpoint");
			} else if (localName.equals("nmBoardingLocation")) {
				this.nmBoardingLocation = true;
			} else if (localName.equals("idBoardingLocation")) {
				this.idBoardingLocation = true;
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg.equals("CITY")) {
				int count = mResponse.mCity_List.size();
				String city[] = new String[count];
				for (int i = 0; i < count; i++)
					city[i] = mResponse.mCity_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(Search.this,
						R.layout.simple_spinner_item, city);
				mCity.setAdapter(Adapter);
				mCity.setEnabled(true);
				String empty[] = new String[0];
				mEditEndLoc.setAdapter(new ArrayAdapter(Search.this,
						R.layout.simple_spinner_item, empty));
			} else if (loginmsg.equals("ROUTE")) {
				int count = mResponse.mRoute_List.size();
				String route[] = new String[count];
				for (int i = 0; i < count; i++)
					route[i] = mResponse.mRoute_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(Search.this,
						R.layout.simple_spinner_item, route);
				mEditEndLoc.setAdapter(Adapter);
				mEditEndLoc.setEnabled(true);
			} else if (loginmsg.equals("BLOCATIONS")) {
				int count = mResponse.mBoarding_List.size();
				String route[] = new String[count];
				for (int i = 0; i < count; i++)
					route[i] = mResponse.mBoarding_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(Search.this,
						R.layout.simple_spinner_item, route);
				mEditBPoint.setAdapter(Adapter);
				mEditBPoint.setEnabled(true);
				if (mSearchType == Search.SEARCH_MORNING
						|| mSearchType == Search.SEARCH_EVENING
						|| mSearchType == Search.SEARCH_LMS_MMTS) {
					count = mResponse.mEnd_List.size();
					String endloc[] = new String[count];
					for (int i = 0; i < count; i++)
						endloc[i] = mResponse.mEnd_List.get(i);
					ArrayAdapter Adapter1 = new ArrayAdapter(Search.this,
							R.layout.simple_spinner_item, endloc);
					mEditEndLoc.setAdapter(Adapter1);
					mEditEndLoc.setEnabled(true);
				}
			}
		}
	};

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.search_submit) {
			
			if(validateInput() == false)
				return;
			
			Intent intent = new Intent();
			intent.setClass(Search.this, SearchResult.class);
			intent.putExtra("typeofSearch", Integer.toString(mSearchType));
			if (mSearchType == SEARCH_ROUTE) {
				intent.putExtra("idRoute", mSelectedRoute);
			} else if (mSearchType == SEARCH_TIME) {
				intent.putExtra("idBoardingLocationId", mSelectedLocation);
				intent
						.putExtra("tsTime", mEditTime.getText().toString()
								.trim());
			} else {
				intent.putExtra("idBoardingLocationId", mStartLocation);
				intent.putExtra("idEndLocationId", mEndLocation);
			}
			startActivity(intent);
		} else if (view.getId() == R.id.search_time) {
			showDialog(TIME_PICKER);
		}
	}
	
	private boolean validateInput() {
		boolean valid = true;
		if(mSearchType == 0 )
			valid = false;
		
		if (mSearchType == SEARCH_ROUTE) {
			if(mSelectedRoute == null){
				Toast.makeText(this, "Select Route", Toast.LENGTH_SHORT).show();
				valid = false;
			}
		} else if (mSearchType == SEARCH_TIME) {
			if(mSelectedLocation == null){
				Toast.makeText(this, "Select Boarding Location", Toast.LENGTH_SHORT).show();
				valid = false;
			}
			if(mEditTime.getText().toString()
					.trim().length() == 0){
				Toast.makeText(this, "Select Time", Toast.LENGTH_SHORT).show();
				valid = false;
			}

		} else {
			if(mStartLocation == null){
				Toast.makeText(this, "Select Boarding Location", Toast.LENGTH_SHORT).show();
				valid = false;
			}
			if(mEndLocation == null){
				Toast.makeText(this, "Select End Location", Toast.LENGTH_SHORT).show();
				valid = false;
			}
		}

		return valid;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final Calendar cal = Calendar.getInstance();
		switch (id) {
		case TIME_PICKER:
			int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
			int minute = cal.get(Calendar.MINUTE);
			return new TimePickerDialog(this, timeListener, hourOfDay, minute,
					true);
		default:
			return super.onCreateDialog(id);
		}
	}

	private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			String hour = String.valueOf(hourOfDay);
			if (hour.length() == 1)
				hour = "0" + hour;
			String minutes = String.valueOf(minute);
			if (minutes.length() == 1)
				minutes = "0" + minutes;
			mEditTime.setText(hour + ":" + minutes + ":" + "00");
		}

	};

}
